from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError


class StockPicking(models.Model):
    _inherit = 'stock.picking'
    qty = fields.Float(string='QTY', compute='_compute_stock_move_qty')

    instruction_id = fields.Many2one('ship.instructions', string='Instructions'
                                     , default=lambda self: self._context.get('default_instruction_id', False))

    @api.depends('move_ids_without_package')
    def _compute_stock_move_qty(self):
        for item in self:
            item.qty = sum(line.product_uom_qty for line in item.move_ids_without_package)

    def button_validate(self):
        for record in self:
            if record.picking_type_id.with_context(lang='zh_CN').name == '销售交货':
                processing_qty = sum(record.move_ids_without_package.mapped('quantity'))
                if record.qty == processing_qty:  # 冇欠数
                    record.instruction_id.state = 'done'
                    record.instruction_id.pd_id.delivery_state = 'done'
                if processing_qty < record.qty:  # 有欠数
                    context = dict(self.env.context)
                    # 如果冇稳到来自边张instruction 会容易出现问题  需要手动绑定翻
                    context.update({
                        'default_instruction_id': record.instruction_id.id if record.instruction_id else False,
                    })
                    self.env.context = context

            return super(StockPicking, record).button_validate()
